package com.yc.testupload.publisher;

import com.yc.testupload.controller.DocumentsServlet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
import java.util.Map;

/**
 * 平台发布器工厂类
 * 负责创建和管理不同平台的发布器实例
 */
public class PlatformPublisherFactory {
    private static final Logger logger = LogManager.getLogger(PlatformPublisherFactory.class);
    private final Map<String, PlatformPublisher> publishers;

    public PlatformPublisherFactory() {
        publishers = new HashMap<>();
        // 初始化各种平台的发布器
        initializePublishers();
    }

    /**
     * 初始化所有平台发布器
     */
    private void initializePublishers() {
        // 添加微信平台发布器
        WechatPublisher wechatPublisher = new WechatPublisher();
        publishers.put(wechatPublisher.getPlatformType(), wechatPublisher);
        publishers.put("0", wechatPublisher); // 0表示微信平台（根据数据库中的类型）

        // 添加微博平台发布器
        WeiboPublisher weiboPublisher = new WeiboPublisher();
        publishers.put(weiboPublisher.getPlatformType(), weiboPublisher);
        publishers.put("1", weiboPublisher); // 1表示微博平台

        // 添加抖音平台发布器
        DouyinPublisher douyinPublisher = new DouyinPublisher();
        publishers.put(douyinPublisher.getPlatformType(), douyinPublisher);
        publishers.put("2", douyinPublisher); // 2表示抖音平台

        logger.info("平台发布器初始化完成，共支持 {} 种平台", publishers.size() / 2);
    }

    /**
     * 设置DocumentsServlet实例，用于微信平台发布功能
     * 
     * @param documentsServlet DocumentsServlet实例
     */
    public void setDocumentsServlet(DocumentsServlet documentsServlet) {
        logger.info("为微信发布器注入DocumentsServlet实例");
        // 获取微信发布器实例并注入DocumentsServlet
        PlatformPublisher publisher = publishers.get("wechat");
        if (publisher instanceof WechatPublisher) {
            ((WechatPublisher) publisher).setDocumentsServlet(documentsServlet);
            logger.info("微信发布器成功注入DocumentsServlet实例");
        } else {
            logger.warn("未找到微信发布器实例，无法注入DocumentsServlet");
        }
    }

    /**
     * 根据平台类型获取发布器
     * 
     * @param platformType 平台类型
     * @return 对应的发布器实例，如果没有找到则返回null
     */
    public PlatformPublisher getPublisher(String platformType) {
        PlatformPublisher publisher = publishers.get(platformType);
        if (publisher == null) {
            logger.warn("未找到平台类型 {} 的发布器", platformType);
        }
        return publisher;
    }

    /**
     * 获取支持的平台类型列表
     * 
     * @return 平台类型列表
     */
    public Map<String, String> getSupportedPlatforms() {
        Map<String, String> platforms = new HashMap<>();
        platforms.put("0", "微信公众号");
        platforms.put("1", "微博");
        platforms.put("2", "抖音");
        return platforms;
    }
}